package com.vanvalt.payhui.modules.pay.api.business;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.vanvalt.payhui.modules.pay.api.command.impl.PageCommand;
import com.vanvalt.payhui.modules.pay.api.command.impl.ProfitCommand;
import com.vanvalt.payhui.modules.pay.api.command.impl.RequestCommand;
import com.vanvalt.payhui.modules.pay.api.command.impl.ResponseCommand;
import com.vanvalt.payhui.modules.pay.api.util.ErrorCode;
import com.vanvalt.payhui.modules.pay.entity.ProfitData;
import com.vanvalt.payhui.modules.pay.service.ProfitDataService;
import com.vanvalt.payhui.modules.pay.service.UserService;
import com.vanvalt.payhui.util.constat.Constant;
import com.vanvalt.payhui.util.json.JsonConversion;

/**
 * 分润处理
 *
 */
public class ProfitProcess extends BaseProcess {
	/**
	 *日志.
	 */
	private static Logger 				logger = Logger.getLogger(ProfitProcess.class);
	/*private static HttpServletRequest	httpServletRequest	= ((ServletRequestAttributes) RequestContextHolder
			.getRequestAttributes()).getRequest();*/
	
	private UserService userService;
	private ProfitDataService profitDataService;
	
	/**
	 * 构造方法.
	 */	
	public ProfitProcess() {
		super();
	}

	/**
	 * @param profitDataService
	 */
	public ProfitProcess(ProfitDataService profitDataService){
		super();
		this.profitDataService = profitDataService;
	}
	
	/**
	 * @param userService
	 * @param profitDataService
	 */
	public ProfitProcess(UserService userService, ProfitDataService profitDataService){
		super();
		this.userService = userService;
		this.profitDataService = profitDataService;
	}

	/**
	 * 分润列表
	 * @param requestCommand
	 * @param responseCommand
	 * @return
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public ResponseCommand list(PageCommand pageCommand, RequestCommand requestCommand, ResponseCommand responseCommand)
			throws JsonParseException, JsonMappingException, IOException {
		
		// 分页参数
		pageCommand = initPagecommand(pageCommand, requestCommand);
		RowBounds rowBounds = new RowBounds(pageCommand.getPage().getOffset(), 
				pageCommand.getPage().getPageSize());
				
		ProfitCommand profitCommand = new ProfitCommand(requestCommand.getObject().toString());
		Map<String, Object> map = profitCommand.getMap();
		String uid = (String) map.get("uid");
        String currentPage = (String) map.get("currentPage");
        String pageSize = (String) map.get("pageSize");
        String year = (String) map.get("year");
        String month = (String) map.get("month");
		
		List<Map<String,Object>> resultList = Lists.newArrayList();
		
		if(map.isEmpty() && StringUtils.isBlank(uid) && StringUtils.isBlank(currentPage) && StringUtils.isBlank(pageSize)){
            return returnResult(ErrorCode.ERR_CODE_STATUS_FALSE, ErrorCode.ERR_CODE_PRECONDITION_FAILED, responseCommand);
        } else {
        	
        	User user = userService.get(uid);
        	
        	if(user == null){
        		return returnResult(ErrorCode.ERR_CODE_STATUS_FALSE, ErrorCode.ERR_CODE_PRECONDITION_FAILED_USER_NOT_EXIST, responseCommand);
        	} else {
        		
        		/*Integer currentPages = Integer.parseInt(currentPage);
                Integer lineSize = Integer.parseInt(pageSize);*/
                
                if(StringUtils.isEmpty(year) || StringUtils.isEmpty(month)){ // 未选择年月
                	
                	 Map<String,Object> ymParams = new HashMap<String,Object>();
                	 ymParams.put("DEL_FLAG_NORMAL", Constant.DEL_FLAG_NORMAL);
                	 ymParams.put("userId", uid);
                	 
                	 List<String> yearMonthList = profitDataService.getYearMonthList(ymParams);
                     
                     int ymSize = yearMonthList.size();
                     
                     if(ymSize > 3){ // 只取最近3个月数据
                     	yearMonthList = yearMonthList.subList(0, 3);
                     }
                     
                     for(String ym:yearMonthList){
                     	
                     	Map<String, Object> resultMap = Maps.newHashMap();
                     	
                     	if(StringUtils.isNotEmpty(ym) && StringUtils.length(ym) == 6){
                     		
                     		String issueYear = ym.substring(0,4);
                     		String issueMonth = ym.substring(4,6);
                     		
                     		resultMap.put("year", issueYear);
                     		resultMap.put("month", issueMonth);
                     		
                     		ProfitData params = new ProfitData();
                     		params.setUserId(uid);
                     		params.setIssueMonth(issueMonth);
                     		params.setIssueYear(issueYear);
                     		// 根据年月获取该用户分润记录
                     		List<ProfitData> profitDatas = profitDataService.findList(params);
                     		// 格式化分润记录
                     		List<Map<String, Object>> pdMapList = this.formatProfitDataList(profitDatas);
                     		
                     		resultMap.put("profitList", pdMapList);
                     	}
                     	
                     	resultList.add(resultMap);
                     }
                } else { 
                	
                	ProfitData pdParams = new ProfitData();
                    pdParams.setDelFlag(Constant.DEL_FLAG_NORMAL); // 正常
                    pdParams.setOffset(rowBounds.getOffset());
                    pdParams.setLimit(rowBounds.getLimit());
                    pdParams.setUserId(uid);
                    
                	if(StringUtils.isNotEmpty(year)){
                    	pdParams.setIssueYear(year);
                    }
                    
                    if(StringUtils.isNotEmpty(month)){
                    	// 格式化月份
                    	int iMonth = Integer.valueOf(month);
                		if(iMonth < 10){
                			month = "0"+iMonth;
                		}
                    	pdParams.setIssueMonth(month);
                    }
                    
                    /*Page<ProfitData> page = profitDataService.findPage(new Page<ProfitData>(currentPages, lineSize), pdParams); 
                    List<ProfitData> profitDataList = page.getList();*/
                    List<ProfitData> profitDataList = profitDataService.findListByPage(pdParams);
                    
                    List<Map<String, Object>> profitDataMapList = this.formatProfitDataList(profitDataList);
                    
                    if(profitDataMapList != null && profitDataMapList.size() > 0){
                    	
                    	Map<String, Object> resultMap = Maps.newHashMap();
                        resultMap.put("year", year);
                        resultMap.put("month", month);
                        resultMap.put("profitList", profitDataMapList);
                        
                        resultList.add(resultMap);
                    }
                }
                
         		return returnResult(ErrorCode.ERR_CODE_STATUS_TRUE, ErrorCode.ERR_CODE_SUCCESS, 
         				JsonConversion.writeListJSON(resultList), responseCommand);
        	}
        }
	}

	private List<Map<String, Object>> formatProfitDataList(List<ProfitData> pdList){
		
		List<Map<String, Object>> pdMapList = Lists.newArrayList();
 		
 		for(ProfitData pd:pdList){
 			Map<String, Object> pdMap = Maps.newHashMap();
 			pdMap.put("platformName", pd.getPlatformName());
 			pdMap.put("amount", pd.getAmount());
 			pdMap.put("date", pd.getCreateDate());
 			pdMap.put("remark", pd.getRemarks());
 			
 			pdMapList.add(pdMap);
 		}
 		
 		return pdMapList;
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public ProfitDataService getProfitDataService() {
		return profitDataService;
	}

	public void setProfitDataService(ProfitDataService profitDataService) {
		this.profitDataService = profitDataService;
	}
	
}
